const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
const $ = _.aggregate;
var that;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    posts: [],
    typeMap: app.globalData.typeMap,
    selectedPage: 0,
    myFollowCount: 0,
    myFansCount: 0,
    userInfo: app.globalData.userInfo,
    _openid: app.globalData._openid,
    statusBarHeight: app.globalData.statusBarHeight,
    navbarHeight: app.globalData.navbarHeight,
    detailInfo: {},
    tempDetailInfo: '',
    showDialog: false,
    tempSkill: ''
    // skillList: ['摸鱼', '前端开发', '计算机科学与技术', '网上冲浪', '哈哈', 'C++']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var user = app.globalData['userInfo'];
    that = this;
    this.setData({
      userInfo: user
    });
    this.getMyPosts();
    this.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 切换tabs选择的列表
   * @param {*} e tabs组件中select事件的参数
   */
  changeList: function (e) {
    var index = e.detail.id;
    console.log(e);
    this.setData({
      selectedPage: index
    });
  },

  /**
   * 获取用户信息（官方接口）
   */
  userProfile: function () {
    console.log('in profile', app.globalData);
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        var userInfo = res.userInfo;
        that.setData({
          userInfo: userInfo
        });
        app.globalData.userInfo = userInfo;
        db.collection('user').add({
          data: userInfo,
          success: function (res) {
            console.log('upload userinfo success');
          },
          fail: function (res) {
            console.log('upload failed')
          }
        });
      },
      fail: (res) => {
        console.log(res);
      }
    });
  },

  /**
   * 获取当前用户所有的帖子
   */
  getMyPosts: function () {
    wx.cloud.callFunction({
      name: 'getUserPost',
      data: {
        limit: 0,
        skip: 0
      }
    }).then((res) => {
      console.log('call res', res);
      that.setData({
        posts: res.result.data
      });
    }).catch((res) => {
      console.log('getUserPost failed', res);
    });
  },

  /**
   * 转到队伍详情页面
   * @param {*} arg tap事件传入的参数
   */
  toArticle: function (arg) {
    console.log('tap article', arg);
    wx.navigateTo({
      url: '../article/index?type=team&id=' + arg.currentTarget.dataset.id,
    });
  },

  /**
   * 获得用户在小程序内填写的信息
   */
  getUserInfo: function () {
    db.collection('user').where({
      _openid: that.data._openid
    }).get().then((res) => {
      console.log('user info res', res);
      that.setData({
        detailInfo: {
          name: res.data[0].name,
          sex: res.data[0].gender == 0 ? '男' : '女',
          school: res.data[0].school,
          major: res.data[0].major,
          grade: res.data[0].grade,
          skillList: res.data[0].skillList,
          introduction: res.data[0].introduction,
        }
      })
    });
  },

  /**
   * 由titledInput组件的input事件触发，修改formData
   * @param {*} arg input事件的参数
   */
  setFormData: function (arg) {
    var name = arg.detail.name,
      value = arg.detail.value;
    console.log('name val', name, value);
    this.data.detailInfo[name] = value == '' ? null : value;
  },

  /**
   * 显示修改信息的Dialog，暂存detailInfo
   */
  showDialog: function () {
    this.setData({
      showDialog: true,
      tempDetailInfo: JSON.stringify(this.data.detailInfo)
    });
  },

  /**
   * 添加skill到skillList
   * @param {*} arg 表单submit事件参数
   */
  addToSkillList: function (arg) {
    console.log('addToSkillList', arg);
    var newSkill = arg.detail.value.newSkill;
    var skillList = this.data.detailInfo.skillList;
    if (newSkill != '') {
      if (skillList == null) {
        this.data.detailInfo.skillList = [newSkill];
      } else {
        var exist = false;
        for (var i in skillList) {
          if (skillList[i] == newSkill) {
            exist = true;
            break;
          }
        }
        if (!exist) {
          skillList.push(newSkill);
          this.setData({
            tempSkill: ''
          });
        } else {
          wx.showToast({
            title: '已存在',
            icon: 'none'
          });
        }
      }
    }

    this.setData({
      'detailInfo.skillList': this.data.detailInfo.skillList
    });
  },

  /**
   * 从skillList中删除元素
   * @param {*} arg tap事件参数
   */
  rmSkillItem: function(arg){
    console.log('remove skill', arg);
    var index = arg.currentTarget.dataset.index;
    this.data.detailInfo.skillList.splice(index, 1);
    this.setData({
      detailInfo: this.data.detailInfo
    });
  },

  /**
   * Dialog关闭时触发，恢复原本的信息
   */
  onDialogHide: function () {
    console.log('dalog closed');
    this.setData({
      detailInfo: JSON.parse(this.data.tempDetailInfo)
    });
  },

  /**
   * 提交个人信息修改
   */
  editSubmit: async function () {
    var modalRes = await wx.showModal({
      title: '提示',
      content: '确定提交吗',
      cancelText: '再看看'
    });
    if (!modalRes.confirm) return;
    db.collection('user').where({
      _openid: this.data._openid
    }).update({
      data: this.data.detailInfo
    }).then((res) => {
      console.log('edit success', res);
      that.setData({
        showDialog: false
      });
      that.getUserInfo();
    }).catch((res) => {
      console.log('edit fail', res);
    });
    // console.log('submit');
    // that.setData({
    //   showDialog: false
    // });
  }
})